const Koa = require("koa")
const KoaRouter = require("koa-router")
const app = new Koa()
const router = new KoaRouter()
const cashbook = require('./config/mysql.js')

app.use(router.routes())
app.use(router.allowedMethods())

router.get('/', (ctx, next) => {
  ctx.body = "Hello"
})

router.get('/bill', async (ctx, next) => {
  ctx.set({ 'Access-Control-Allow-Origin': 'http://localhost:8080' })
  let query = 'select categories.name, bill.amount, bill.type, bill.time from bill INNER JOIN categories on categories.id = bill.category;'
  let res = await cashbook(query)
  ctx.body = {
    res: res
  }
})

router.get('/categories', async (ctx, next) => {
  ctx.set({ 'Access-Control-Allow-Origin': 'http://localhost:8080' })
  let query = 'select name from categories'
  let res = await cashbook(query)
  ctx.body = {
    res: res
  }
})

app.listen('3000', (err) => {
  console.log("Server is running at http://localhost:3000")
})
